<template>
  <div class="remind-edit">
    <van-nav-bar title="编辑提醒" left-text="返回" left-arrow @click-left="onClickLeft" />
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="form.name"
          name="name"
          label="名称"
          placeholder="请输入提醒名称"
          :rules="[{ required: true, message: '请输入提醒名称' }]"
        />
        <van-field
          v-model="form.content"
          name="content"
          label="内容"
          placeholder="请输入内容"
          :rules="[{ required: false, message: '请填写内容' }]"
        />
        <van-field
          v-model="form.email"
          name="email"
          label="邮箱"
          placeholder="请输入提醒邮箱"
          :rules="[{ required: true, message: '请输入提醒邮箱' }]"
        />
        <van-field
          v-model="form.remindTime"
          name="remindTime"
          label="提醒时间"
          placeholder="请选择提醒时间"
          readonly
          @click="showPopup('date')"
        />
        <van-field
          v-model="form.remindType"
          name="remindType"
          label="提醒类型"
          placeholder="请选择提醒类型"
          :rules="[{ required: true, message: '请选择提醒类型' }]"
          readonly
          @click="showPopup('type')"
        />
        <van-field
          v-model="form.state"
          name="state"
          label="状态"
          autocomplete="off"
          placeholder="请输入状态"
          @click="showState"
          readonly
          :rules="[{ required: true, message: '请填写提醒状态' }]"
        />
      </van-cell-group>

      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit"> 保存 </van-button>
      </div>
    </van-form>

    <van-popup :show="showPopupVisible" position="bottom" round>
      <van-picker-group
        v-if="popupType === 'date'"
        title="选择提醒时间"
        :tabs="['选择日期', '选择时间']"
        next-step-text="下一步"
        @confirm="onDateConfirm"
        @cancel="showPopupVisible = false"
      >
        <van-date-picker v-model="currentDate" :min-date="minDate" />
        <van-time-picker v-model="currentTime" />
      </van-picker-group>
      <van-picker
        v-if="popupType === 'type'"
        v-model="currentType"
        :columns="typeColumns"
        title="选择提醒类型"
        @confirm="onTypeConfirm"
        @cancel="showPopupVisible = false"
      />
      <van-picker
        v-if="popupType === 'status'"
        v-model="currentStatus"
        :columns="statusColumns"
        title="选择状态"
        @confirm="onStatusConfirm"
        @cancel="showPopupVisible = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import { updateRemind } from '@/requests/remindItem'
import { getDictionary } from '@/requests/dictionary'

const route = useRoute()
const router = useRouter()
const form = ref({
  id: '',
  name: '',
  email: '',
  remindTime: '',
  remindType: '',
  content: '',
  state: ''
})
const showPopupVisible = ref(false)
const popupType = ref('')
const minDate = new Date()
const typeColumns = ref([])
const statusColumns = ref([])
const currentDate = ref([new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()])
const currentTime = ref([new Date().getHours(), new Date().getMinutes()])
const currentType = ref([])
const currentStatus = ref([])

const formatNumber = num => {
  return num < 10 ? `0${num}` : num
}

onMounted(() => {
  const remindItem = route.query.remindItem
  if (remindItem) {
    const item = JSON.parse(remindItem)
    form.value = {
      id: item.id,
      name: item.name,
      email: item.email,
      remindTime: item.remindTime,
      remindType: item.remindType,
      content: item.content,
      state: item.state
    }

    // 设置当前日期和时间
    const date = new Date(item.remindTime)
    currentDate.value = [date.getFullYear(), date.getMonth() + 1, date.getDate()]
    currentTime.value = [date.getHours(), date.getMinutes()]
  }

  getDictionary('REMIND_TYPE', data => {
    typeColumns.value = data
    if (typeColumns.value.length > 0) {
      currentType.value = [typeColumns.value.find(item => item.value === form.value.remindType)]
    }
  })

  getDictionary('REMIND_STATE', data => {
    statusColumns.value = data
    if (statusColumns.value.length > 0) {
      currentStatus.value = [statusColumns.value.find(item => item.value === form.value.state)]
    }
  })
})

const showPopup = type => {
  popupType.value = type
  showPopupVisible.value = true
}

const onDateConfirm = () => {
  const [year, month, day] = currentDate.value
  const [hour, minute] = currentTime.value
  form.value.remindTime = `${year}-${formatNumber(month)}-${formatNumber(day)} ${formatNumber(hour)}:${formatNumber(minute)}`
  showPopupVisible.value = false
}

const onTypeConfirm = ({ selectedValues }) => {
  form.value.remindType = selectedValues[0]
  showPopupVisible.value = false
}

const onStatusConfirm = ({ selectedValues }) => {
  form.value.state = selectedValues[0]
  showPopupVisible.value = false
}

const showState = () => {
  popupType.value = 'status'
  showPopupVisible.value = true
}

const onClickLeft = () => {
  router.back()
}

const onSubmit = async () => {
  try {
    const res = await updateRemind(form.value.id, form.value)
    if (res.code === 200) {
      showToast({
        type: 'success',
        message: '更新成功',
        duration: 1500
      })
      router.back()
    } else {
      showToast({
        type: 'fail',
        message: res.message || '更新失败',
        duration: 1500
      })
    }
  } catch (error) {
    showToast({
      type: 'fail',
      message: '网络错误，请稍后重试',
      duration: 1500
    })
  }
}
</script>

<style scoped lang="scss">
.remind-edit {
  min-height: 100vh;
  background-color: #f7f8fa;
}
</style>
